package work823;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class work5Client {
  public static void main(String[] args) {
    InetAddress ia = null;
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入问题：");
    try {
   while (true){
     String str = sc.next();
     //获取本机地址
     ia = InetAddress.getByName("localhost");
     //创建DatagramPacket对象，封装数据
     DatagramPacket dp = new DatagramPacket(str.getBytes(),str.getBytes().length,ia,8888);
     //创建DatagramScocket对象，向服务器发送数据
     DatagramSocket ds = new DatagramSocket();
     ds.send(dp);
     //接受服务端响应
     byte[] buf = new byte[1024];
     DatagramPacket dp2 = new DatagramPacket(buf,buf.length);
     ds.receive(dp2);
     String str2 = new String(dp2.getData(),0,dp2.getLength());
     System.out.println(dp2.getAddress().getHostAddress()+"说："+str2);
     if (str2.equals("bye")){
       ds.close();
       break;
     }
   }
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
